﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Security.Cryptography;

namespace AIConvertTool
{
    internal class AIConvert
    {
        private static readonly HttpClient client = new HttpClient();
        static string iniPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.ini");
        IniFiles ini = new IniFiles(iniPath);

        private string AI_TYPE, API_URL, API_KEY, API_MODEL, YIYAN_API_URL, YIYAN_API_KEY, YIYAN_API_MODEL, QWEN_API_URL, QWEN_API_KEY, QWEN_API_MODEL, ZBLOG_USE, ZBLOG_USERNAME, ZBLOG_PASSWORD;
        public AIConvert()
        {
            AI_TYPE = ini.IniReadValue("AISetting", "AI_TYPE");
            API_URL = ini.IniReadValue("AISetting", "API_URL");
            API_KEY = ini.IniReadValue("AISetting", "API_KEY");
            API_MODEL = ini.IniReadValue("AISetting", "API_MODEL");
            YIYAN_API_URL = ini.IniReadValue("AISetting", "YIYAN_API_URL");
            YIYAN_API_KEY = ini.IniReadValue("AISetting", "YIYAN_API_KEY");
            YIYAN_API_MODEL = ini.IniReadValue("AISetting", "YIYAN_API_MODEL");
            QWEN_API_URL = ini.IniReadValue("AISetting", "QWEN_API_URL");
            QWEN_API_KEY = ini.IniReadValue("AISetting", "QWEN_API_KEY");
            QWEN_API_MODEL = ini.IniReadValue("AISetting", "QWEN_API_MODEL");
            ZBLOG_USE = ini.IniReadValue("ZBlog", "USE");
            ZBLOG_USERNAME = ini.IniReadValue("ZBlog", "USERNAME");
            ZBLOG_PASSWORD = ini.IniReadValue("ZBlog", "PASSWORD");
        }

        public async Task<string> SimplifyTextWithAI(string inputPrompt, string inputContent)
        {
            if (AI_TYPE == "1")
            {
                // 请求URL
                string apiUrl = API_URL;

                var zblogRequestData = new ZBlogChatCompletionRequest
                {
                    model = API_MODEL,
                    variables = new ZBlogVariables
                    {
                        username = ZBLOG_USERNAME,
                        password = GetMd5Hash(ZBLOG_PASSWORD),
                        savedate = 30
                    },
                    messages = new[]
                    {
                        new ChatMessage { role = "user", content = inputContent }
                    }
                };

                // 构建请求正文
                var requestData = new ChatCompletionRequest
                {
                    model = API_MODEL,
                    messages = new[] 
                    {
                        new ChatMessage { role = "system", content = inputPrompt },
                        new ChatMessage { role = "user", content = inputContent }
                    }
                };

                string requestBodyJson;
                if (ZBLOG_USE == "1")
                {
                    requestBodyJson = JsonSerializer.Serialize(zblogRequestData);
                } else
                {
                    requestBodyJson = JsonSerializer.Serialize(requestData);
                }

                // return requestBodyJson;
                // 创建HttpClient实例
                using HttpClient httpClient = new HttpClient();

                // 设置请求头
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY);
                // 设置请求的超时时间为30秒
                httpClient.Timeout = TimeSpan.FromSeconds(30);
                string desiredMessage = "<!--返回异常-->";

                try
                {
                    // 发送POST请求
                    using StringContent content = new StringContent(requestBodyJson, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await httpClient.PostAsync(apiUrl, content);
                
                    // 检查响应状态码
                    response.EnsureSuccessStatusCode();


                    // 读取并返回响应正文
                    string responseBody = await response.Content.ReadAsStringAsync();

                    // 使用 JsonDocument 反序列化 JSON 字符串
                    JsonDocument resultDoc = JsonDocument.Parse(responseBody);

                    // 通过对象导航访问所需字段
                    JsonElement choicesElement = resultDoc.RootElement.GetProperty("choices")[0];
                    JsonElement messageElement = choicesElement.GetProperty("message");
                    try
                    {
                        desiredMessage = messageElement.GetProperty("content").GetString();
                    }
                    catch { }

                    // 输出提取的消息内容
                    // Console.WriteLine(desiredMessage); // 输出：“电影《铃芽之旅》的导演是新海诚。”

                    // 不忘记释放 JsonDocument
                    resultDoc.Dispose();

                    //}
                    //catch (TaskCanceledException ex) when (ex.CancellationToken.IsCancellationRequested)
                    //{
                }
                catch { }
                return desiredMessage;
            }
            if (AI_TYPE == "2")
            {

                string[] apiKey = YIYAN_API_KEY.Split("|");

                string tokenUrl = $"{YIYAN_API_URL}/oauth/2.0/token?grant_type=client_credentials&client_id={apiKey[0]}&client_secret={apiKey[1]}";

                string token;
                HttpResponseMessage tokenResponse = await client.GetAsync(tokenUrl);

                if (tokenResponse.IsSuccessStatusCode)
                {
                    string tokenResponseBody = await tokenResponse.Content.ReadAsStringAsync();
                    JsonDocument resultToken = JsonDocument.Parse(tokenResponseBody);
                    token = resultToken.RootElement.GetProperty("access_token").GetString();
                }
                else
                {
                    throw new HttpRequestException($"Failed to get access token. Status code: {tokenResponse.StatusCode}");
                }

                // 请求URL
                string apiUrl = $"{YIYAN_API_URL}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/{YIYAN_API_MODEL}?access_token={token}";

                // 构建请求正文
                var requestData = new YInput
                {
                    messages = new[] {
                        new ChatMessage { role = "user", content = inputContent }
                    },
                    system = inputPrompt
                };
                string requestBodyJson = JsonSerializer.Serialize(requestData);

                // 创建HttpClient实例
                using HttpClient httpClient = new HttpClient();

                // 设置请求头
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // 发送POST请求
                using StringContent content = new StringContent(requestBodyJson, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await httpClient.PostAsync(apiUrl, content);

                try
                {
                    // 检查响应状态码
                    response.EnsureSuccessStatusCode();
                }
                catch
                {
                    return $"<!--返回异常-->";
                }

                // 读取并返回响应正文
                string responseBody = await response.Content.ReadAsStringAsync();

                // 使用 JsonDocument 反序列化 JSON 字符串
                JsonDocument resultDoc = JsonDocument.Parse(responseBody);
                // 通过对象导航访问所需字段
                string textElement = "<!--返回异常-->";
                try
                {
                    textElement = resultDoc.RootElement.GetProperty("result").GetString();
                }
                catch { }

                // 输出提取的消息内容
                // Console.WriteLine(desiredMessage); // 输出：“电影《铃芽之旅》的导演是新海诚。”

                // 不忘记释放 JsonDocument
                resultDoc.Dispose();

                return textElement;
            }
            if (AI_TYPE == "3")
            {
                // 请求URL
                string apiUrl = QWEN_API_URL;

                var inputMessage = new Input
                {
                    messages = new[] {
                        new ChatMessage { role = "system", content = inputPrompt },
                        new ChatMessage { role = "user", content = inputContent }
                    }
                };
                // 构建请求正文
                var requestData = new TextGeneration
                {
                    model = QWEN_API_MODEL,
                    input = inputMessage
                };
                string requestBodyJson = JsonSerializer.Serialize(requestData);
                // 创建HttpClient实例
                using HttpClient httpClient = new HttpClient();

                // 设置请求头
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", QWEN_API_KEY);

                // 发送POST请求
                using StringContent content = new StringContent(requestBodyJson, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await httpClient.PostAsync(apiUrl, content);
                try
                {
                    // 检查响应状态码
                    response.EnsureSuccessStatusCode();
                }
                catch
                {
                    return $"<!--返回异常-->";
                }

                // 读取并返回响应正文
                string responseBody = await response.Content.ReadAsStringAsync();

                // 使用 JsonDocument 反序列化 JSON 字符串
                JsonDocument resultDoc = JsonDocument.Parse(responseBody);

                // 通过对象导航访问所需字段
                JsonElement outputElement = resultDoc.RootElement.GetProperty("output");
                string textElement = "<!--返回异常-->";
                try
                {
                    textElement = outputElement.GetProperty("text").GetString();
                }
                catch { }

                // 输出提取的消息内容
                // Console.WriteLine(desiredMessage); // 输出：“电影《铃芽之旅》的导演是新海诚。”

                // 不忘记释放 JsonDocument
                resultDoc.Dispose();

                return textElement;
            } else
            {
                return "未选择模型接口?";
            }
        }

        static string GetMd5Hash(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sb.Append(data[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

    }
    

    // 定义请求数据类
    public class ChatCompletionRequest
    {
        public string model { get; set; }
        public ChatMessage[] messages { get; set; }
    }

    public class ZBlogChatCompletionRequest
    {
        public string model { get; set; }
        public ZBlogVariables variables { get; set; }
        public ChatMessage[] messages { get; set; }
    }

    public class ZBlogVariables
    {
        public string username { get; set; }
        public string password { get; set; }
        public int savedate { get; set; }
    }

    public class ChatMessage
    {
        public string role { get; set; }
        public string content { get; set; }
    }

    // 定义一个类来匹配JSON结构（仅包含所需字段）
    public class ChatChoice
    {
        public ChatMessage message { get; set; }
    }

    public class TextGeneration
    {
        public string model { get; set; }
        public Input input { get; set; }
    }

    public class Input
    {
        public ChatMessage[] messages { get; set; }
    }

    public class YInput
    {
        public ChatMessage[] messages { get; set; }
        public string system { get; set; }
    }

}
